package com.rainng.coursesystem.service.teacher;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rainng.coursesystem.dao.mapper.AnswerMapper;
import com.rainng.coursesystem.dao.mapper.StudentMapper;
import com.rainng.coursesystem.model.entity.AnswerEntity;
import com.rainng.coursesystem.model.entity.StudentEntity;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.model.vo.response.table.AnswerVO;
import com.rainng.coursesystem.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AnswerService extends BaseService {

    @Autowired
    private AnswerMapper answerMapper;


    @Autowired
    private StudentMapper studentMapper;

    public ResultVO listAnswer(Integer homeworkId) {

        List<AnswerEntity> answerList = answerMapper.selectList(new QueryWrapper<AnswerEntity>().eq("homework_id", homeworkId));
        List<Integer> studentIds = answerList.stream().map(AnswerEntity::getStudentId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(studentIds)) {
            return result("");
        }
        Map<Integer, StudentEntity> studentMap = studentMapper.selectBatchIds(studentIds).stream().collect(Collectors.toMap(StudentEntity::getId, c -> c));

        List<AnswerVO>  voList = new ArrayList<>();

        for (AnswerEntity answer : answerList) {
            AnswerVO vo = new AnswerVO();
            BeanUtils.copyProperties(answer,vo);
            StudentEntity studentEntity = studentMap.get(vo.getStudentId());
            vo.setStudentName(studentEntity.getName());
            vo.setStudentNumber(studentEntity.getNumber());
            voList.add(vo);
        }

        return result(voList);
    }

}
